package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.sunnyday.dao.OrderSettingDao;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.OrderSetting;
import com.xrit.sunnyday.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettings) {
        for (OrderSetting orderSetting : orderSettings) {
            Date orderDate = orderSetting.getOrderDate();
            OrderSetting osInDb = orderSettingDao.findByOrderDate(orderDate);
            if (null != osInDb) {
                if (osInDb.getReservations() > orderSetting.getNumber()) {
                    throw new SunnydayException(orderSetting.getOrderDate() + "中，已预约的人数比你现在设置的可预约人数要大");
                }
                orderSettingDao.updateNumber(orderSetting);
            } else {
                orderSettingDao.add(orderSetting);
            }
        }

    }

    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String month) {
        String startDate = month + "-01";
        return orderSettingDao.getOrderSettingByMonth(startDate);
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //获取前端传递过来的日期
        Date orderDate = orderSetting.getOrderDate();
        //通过日期判断预约设置是否存在？
        OrderSetting order = orderSettingDao.findByOrderDate(orderDate);
        //- 存在：
        if (null != order) {
            // 判断已经预约的人数是否大于要更新的最大可预约人数， reverations > 传进来的number数量，则不能更新，要报错
            if (order.getReservations() > orderSetting.getNumber()) {
                // 已经预约的人数高于最大预约人数，不允许
                throw new SunnydayException("最大预约人数不能小已预约人数！");
            }
            // reverations <= 传进来的number数量，则要更新最大可预约数量
            orderSettingDao.editNumberByDate(orderSetting);
        } else {
            //- 不存在：
            //  - 添加预约设置信息
            orderSettingDao.add(orderSetting);
        }

    }
}
